#include<iostream>

#include<stdio.h>

#include<string>

#include <sys/types.h>

#include <sys/socket.h>

#include <netinet/in.h>

#include <arpa/inet.h>

#include<unistd.h>

#include<string.h>

#include <pthread.h>

#define SIZE 1024

enum
{
    SOCKETERR = 1,
    BINDERR,
    ARGCERR
};

struct task
{
    int sockfd;
    sockaddr_in in;
};

void* read_thread(void* arg)
{
    task* tkptr = static_cast<task*>(arg);
    char buffer[SIZE] = {0};
    while(1)
    {
        sockaddr_in temp;
        socklen_t len = sizeof(temp);
    
        ssize_t ret = recvfrom(tkptr->sockfd, buffer, SIZE, 0, (sockaddr*)&temp, &len);
    
        buffer[ret] = 0;
    
        if(ret > 0) std::cerr << buffer << std::endl;
    }
}

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        std::cout << "3 wrods! error" << std::endl;
        exit(ARGCERR);
    }
    
    task tk;

    tk.sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(tk.sockfd < 0)
    {
        perror("socket");
        exit(SOCKETERR);
    }

    bzero(&(tk.in), sizeof(tk.in));

    uint16_t serverport = std::stoi(argv[2]);
    tk.in.sin_addr.s_addr = inet_addr(argv[1]);
    tk.in.sin_family = AF_INET;
    tk.in.sin_port = htons(serverport);

    pthread_t PT;
    pthread_create(&PT, nullptr, read_thread, (void*)&tk);

    std::string message;
    while(1)
    {
        std::cout << "please enter# ";
        std::getline(std::cin, message);
        if(sendto(tk.sockfd, message.c_str(), message.size(), 0, (sockaddr*)&(tk.in), sizeof(tk.in)) < 0)
        {
            perror("sendto");
        }
    }
    close(tk.sockfd);
    return 0;
}